import {request, storeAccessToken, deleteToken, takeAccessToken} from '@/utils/request';
import {ElMessage} from 'element-plus';

const defaultFailure = (message, status, url) => {
    console.warn(`请求地址: ${url}, 状态码: ${status}, 错误信息: ${message}`);
    ElMessage.warning(message);
};

export function login(username, password, remember, success, failure = defaultFailure) {
    request.post('/auth/login', {
        username: username,
        password: password
    }).then(data => {
        if (data.code === 200) {
            storeAccessToken(data.token, data.expire, remember);
            ElMessage.success(`登录成功，欢迎 ${data.username} 来到我们的系统`);
            success(data);
        } else {
            failure(data.message, data.code, '/auth/login');
        }
    }).catch(error => {
        console.error(error);
        ElMessage.error('发生了一些错误，请联系管理员');
    });
}

export function logout(success, failure = defaultFailure) {
    request.get('/auth/logout',
        {headers: {'Authorization': `Bearer ${takeAccessToken()}`}}
    )
        .then(data => {
            if (data.code === 200) {
                deleteAccessToken();
                ElMessage.success(`退出登录成功，欢迎您再次使用`);
                success();
            } else {
                failure(data.message, data.code, '/auth/logout');
            }
        }).catch(error => {
        console.error(error);
        ElMessage.error('发生了一些错误，请联系管理员');
    });
}

export function unauthorized() {
    return !takeAccessToken();
}
